package com.kmist.xiakexing.presenters;

import android.util.Log;

import com.kmist.xiakexing.data.UserDao;
import com.kmist.xiakexing.interfaces.IUserCallback;
import com.kmist.xiakexing.interfaces.IUserPreserter;
import com.kmist.xiakexing.main.socket.DataRecver;
import com.kmist.xiakexing.main.socket.ISocketCallback;
import com.kmist.xiakexing.main.socket.SockPresenter;
import com.kmist.xiakexing.main.socket.DataSender;
import com.kmist.xiakexing.main.socket.cmd;
import com.kmist.xiakexing.main.socket.retCode;
import com.kmist.xiakexing.utils.UserBean;

import org.json.JSONObject;

public class UserPreserter implements IUserPreserter, ISocketCallback {

    private static UserPreserter sInstance;

    private IUserCallback mCallback;
    private final PlayerPresenter playerPresenter;
    private final SockPresenter sockPresenter;

    public static UserPreserter getsInstance() {
        if (sInstance == null) {
            synchronized (UserPreserter.class){
                sInstance = new UserPreserter();
            }
        }
        return sInstance;
    }

    public UserPreserter() {
        sockPresenter = SockPresenter.getInstance();
        sockPresenter.setCallback(this);
        playerPresenter = PlayerPresenter.getInstance();
    }

    @Override
    public void setCallback(IUserCallback callback) {
        this.mCallback = callback;
    }

    @Override
    public void login(UserBean userBean) {
        DataSender info = new DataSender(cmd.CMD_LOGIN, userBean.toString());
        info.setSendLength(info.toString().length());
        sockPresenter.sendMessage(info.toString());
    }

    @Override
    public void register() {

    }


    @Override //sock
    public void onConnected() {
        mCallback.onConnected();
    }

    @Override //sock
    public void onNetworkError() {
        mCallback.onNetworkError();
    }

    @Override //sock
    public void onDataRecved(DataRecver dataRecver) {
        if (!dataRecver.getResp_cmd().equals(cmd.CMD_LOGIN)) {
            return;
        }

        switch (dataRecver.getResp_code()){
            case retCode.RET_OK:{

                try {
                    JSONObject resp_data = new JSONObject(dataRecver.getResp_data());
                    String sid = resp_data.getString("sid");
                    playerPresenter.setPlayerSid(sid);
                    mCallback.onLoginSuccess();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            } break;
            case retCode.ERRCD_NOACCOUNT:
            case retCode.ERRCD_PASSWDERR:
                Log.d("RECV:",""+dataRecver.getResp_code());
                mCallback.onLoginError();
                break;
        }

    }
}
